/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  cleanUpQcForm
 *  CleanUpQcForm
 *  clean_up_qc_form
 *  set panel.id
 */



/***** variables declartion section, begin *****/
var cleanUpQcFormInputMode = wacFormInputMode.add;
var cleanUpQcFormObj = {};
var cleanUpQcFormAuditAction = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        cleanUpQcFormAuditAction = new CleanUpQcFormAuditAction();

        initCleanUpQcFormFormDialog();

        initCleanUpQcFormForm();

        bindCleanUpQcFormEvents();
    }
);

function bindCleanUpQcFormEvents()
{
    $("#cleanUpQcFormFormDialog").bind('dialogopen', function(event, ui)
    {
        initCleanUpQcFormFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.cleanUpQcForm.name);//
    });

    $("#cleanUpQcFormFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#cleanUpQcForm_btnSubmit").bind('click', function (e)
    {
        submitCleanUpQcFormForm();
    });

    $("#cleanUpQcForm_btnClose").bind('click', function (e)
    {
        $("#cleanUpQcFormFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t1062")
        {
            $("div[aria-labelledby='ui-dialog-title-cleanUpQcFormFormDialog']").remove();
            $("#cleanUpQcFormFormDialog").remove();
        }
    });
}


function initCleanUpQcFormFormDialog()
{
//    wacDebugLog("initCleanUpQcFormFormDialog.");
    $("#cleanUpQcFormFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 1050,
            height: 580,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCleanUpQcFormForm()
{
    $("#cleanUpQcFormForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#cleanUpQcForm_qc_date").datepicker();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initCleanUpQcFormFormData()
{
    wacShowBlockUILoading("#cleanUpQcFormFormDialog");
    $('#cleanUpQcForm_production_order_id, #cleanUpQcForm_clean_up_form_id, #cleanUpQcForm_goods_category_id').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "cleanUpQcForm/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCleanUpQcFormFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCleanUpQcFormFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#cleanUpQcForm_check_length_unit_code");
        }
   }

   setupCleanUpQcFormFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#cleanUpQcFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCleanUpQcFormFormDefaultValues(defaultValueObj)
{
    if(cleanUpQcFormInputMode == wacFormInputMode.add)   // use default values
    {
        $("#cleanUpQcForm_id").attr("value", 0);
        $('#cleanUpQcForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cleanUpQcForm_clean_up_form_id').flexbox(BASE_URL + 'cleanUpForm/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "clean_up_form_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cleanUpQcForm_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#cleanUpQcForm_check_length_unit_code option:[value='"+ defaultValueObj.check_length_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#cleanUpQcForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cleanUpQcFormObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpQcForm_production_order_id_input').val(cleanUpQcFormObj.production_order_code);

        $('#cleanUpQcForm_clean_up_form_id').flexbox(BASE_URL + 'cleanUpForm/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cleanUpQcFormObj.clean_up_form_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "clean_up_form_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpQcForm_clean_up_form_id_input').val(cleanUpQcFormObj.clean_up_form_code);

        $('#cleanUpQcForm_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cleanUpQcFormObj.goods_category_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
                wacDebugLog('You selected "' + this.value + '", ' +
                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpQcForm_goods_category_id_input').val(cleanUpQcFormObj.goods_category_name);

        $("#cleanUpQcForm_hole_check_memo").attr("value", cleanUpQcFormObj.hole_check_memo);
        $("#cleanUpQcForm_edge_check_memo").attr("value", cleanUpQcFormObj.edge_check_memo);
        $("#cleanUpQcForm_fold_check_memo").attr("value", cleanUpQcFormObj.fold_check_memo);
        $("#cleanUpQcForm_spot_check_memo").attr("value", cleanUpQcFormObj.spot_check_memo);

        $("#cleanUpQcForm_qc_date").attr("value", cleanUpQcFormObj.qc_date);
        $("#cleanUpQcForm_code").attr("value", cleanUpQcFormObj.code);
        $("#cleanUpQcForm_id").attr("value", cleanUpQcFormObj.id);
        $("#cleanUpQcForm_memo").attr("value", cleanUpQcFormObj.memo);

        $("#cleanUpQcForm_hole_check").attr("checked", (cleanUpQcFormObj.hole_check==1));
        $("#cleanUpQcForm_edge_check").attr("checked", (cleanUpQcFormObj.edge_check==1));
        $("#cleanUpQcForm_fold_check").attr("checked", (cleanUpQcFormObj.fold_check==1));
        $("#cleanUpQcForm_spot_check").attr("checked", (cleanUpQcFormObj.spot_check==1));

        $("#cleanUpQcForm_touch_check").attr("checked", (cleanUpQcFormObj.touch_check==1));
        $("#cleanUpQcForm_luster_check").attr("checked", (cleanUpQcFormObj.luster_check==1));
        $("#cleanUpQcForm_color_check").attr("checked", (cleanUpQcFormObj.color_check==1));
        $("#cleanUpQcForm_cloth_check").attr("checked", (cleanUpQcFormObj.cloth_check==1));
    }

//    wacDebugLog($.dump(cleanUpQcFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("cleanUpQcFormInputMode: " + cleanUpQcFormInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function CleanUpQcFormAuditAction(){
    this.run = function(orderId){
        cleanUpQcFormAudit(orderId);
    }
}

function cleanUpQcFormAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "clean_up_qc_form_id" : orderId
    };
//    cleanUpQcFormObj = $("#cleanUpQcFormList").getRowData(orderId);
//    console.log($.dump(cleanUpQcFormObj));

    $.ajax({
        url: BASE_URL + "cleanUpQcForm/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            cleanUpQcFormAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function cleanUpQcFormAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cleanUpQcFormList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function cleanUpQcFormOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    cleanUpQcFormInputMode = inputMode;

    if(rowid === undefined){
        cleanUpQcFormObj = {};
    }
    else
    {
        cleanUpQcFormObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCleanUpQcFormForm()
{
    var validateFlag = true;

    if (!$("#cleanUpQcFormForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }
    

    return validateFlag;
}

function submitCleanUpQcFormForm()
{
    if(!validateCleanUpQcFormForm()){
        return;
    }

    wacShowBlockUILoading("#cleanUpQcFormFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(cleanUpQcFormInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "cleanUpQcForm/add";
    }
    else{
        submitUrl = BASE_URL + "cleanUpQcForm/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#cleanUpQcFormForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCleanUpQcFormFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCleanUpQcFormFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cleanUpQcFormList").trigger("reloadGrid");
   }

   wacHideBlockUI("#cleanUpQcFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/